package ibatis;

import gui.common.msg.MsgType;
import gui.common.msg.SysMessage;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapException;


import data.Count;
import data.Forum;
import data.Message;
import data.dao.MessageDao;

public class SqlMapMessageDao implements MessageDao{

	private SqlMapClient sd=SqlConfig.getSqlMapInstance();

	
	public SysMessage createNewMessage(Message msg) throws SQLException {
		SysMessage sMsg=new SysMessage();
		if(msg.getId()<1){
			int seed=SeedProvider.getSeed(Message.SeedName);
			msg.setId(seed);
		}
		if(msg.getTime()==null){
			msg.setTime(new Date(System.currentTimeMillis()));
		}
		sMsg.subject="Create Message";
		try {
			sd.insert("insertMessage",msg);
			sMsg.type=MsgType.Success;
			sMsg.detail="New message is added!";
			sMsg.data=msg;
		} catch (Exception e) {
			sMsg.type=MsgType.Error;
			sMsg.detail=e.getMessage();
			e.printStackTrace();
		}
		return sMsg;

	}

	public SysMessage deleteMessage(Message msg) throws SQLException {
		// TODO Auto-generated method stub
		SysMessage msg1=new SysMessage();
		sd.delete("deleteMessage", msg);
		if(sd.queryForObject("getMessageById",msg.getId())!=null){
			msg1.type=MsgType.Error;
			msg1.subject="delete user failed";
		}else{
			msg1.type=MsgType.Success;
			msg1.subject="delete user success";
		}
		return msg1;
	}

	public List<Message> getMesaList(Forum forum, int start, int end) throws SQLException {
		// TODO Auto-generated method stub
		return (List<Message>)sd.queryForList("getMessageList",forum,start,end);
	}

	public Count getMessageCount(Forum forum) throws SQLException {
		// TODO Auto-generated method stub
		return (Count)sd.queryForList("getMessageCount");
	}

	public List<Message> getMessageList(Forum forum) throws SQLException {
		return (List<Message>)sd.queryForList("getMessageList",forum);
	}

	public SysMessage updateMessage(Message msg) throws SqlMapException {
		// TODO Auto-generated method stub
		SysMessage msg1=new SysMessage();
		msg1.subject="Update Message";
		Message oldMessage;
		try {
			oldMessage = (Message)sd.queryForObject("getMessageById",msg.getId());

			if(oldMessage!=null){

				if(oldMessage.getMessage().equals(msg.getMessage())){
					msg1.type=MsgType.Warning;
					msg1.subject="Need not update";
				}else {
					sd.update("updateMessage", msg);
					msg1.type=MsgType.Success;
					msg1.subject="Update User success";
				}

			}else{
				msg1.type=MsgType.Error;
				msg1.detail="No such user:"+msg.getId();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return msg1;
	}

	public Message getMessageById(int id) throws SQLException {
		Message message=null;
		message=(Message)sd.queryForObject("getMessageById", id);
		return message;
	}
}
